package com.example.landlord.demo.utils.system;

import org.java_websocket.WebSocket;

import java.util.Collection;
import java.util.concurrent.CopyOnWriteArraySet;

public class UsersOperationSystem {
    private static volatile Collection<User> userCollection = new CopyOnWriteArraySet<>();

    public Collection<User> getUsers(){
        return userCollection;
    }

    public synchronized void addUser(WebSocketMessage webSocketMessage){
        //查找是否有重复的用户
        for(User u : userCollection){
            if(u.id.equals(webSocketMessage.id)){
                System.out.println("找到了已注册用户，将只替换套接字");
                //已经认证过的用户，将用当前连接来代替旧连接
                System.out.println("");
                u.picture=webSocketMessage.picture;
                u.webSocket.close();
                u.webSocket= webSocketMessage.webSocket;
                //检查该用户断线之前是否有正在进行的游戏
                if(u.gameType!=GameType.NOGAME){
                    //有正在进行的游戏，就让用户继续玩游戏
                    u.game.playerReloading(u);
                }
                return;
            }
        }
        //创建user实体
        User user = new User();
        user.name = webSocketMessage.name;
        user.id = webSocketMessage.id;
        user.picture = webSocketMessage.picture;
//        System.out.println(user.picture);
        user.webSocket= webSocketMessage.webSocket;
        //加入客户列表
        userCollection.add(user);
        System.out.println(user.name+"加入了系统");
    }

    public synchronized boolean removeUser(WebSocket webSocket){
        //查找是哪个用户退出，从列表中删除它
        User user = getUserBySocket(webSocket);
        if(user!=null){
//            userCollection.remove(user);
            if(user.gameType!=GameType.NOGAME){
                //该玩家还加入有其他游戏,一并移除
                Player p =new Player(user);
                if(user.game.gameStatus==GameStatus.WAITING){
                    //如果该用户的游戏还处于等待阶段，则从游戏里移出它
                    p.user.game.removePlayer(p);
                }else{
                    //如果该用户游戏已经开始，就不删除该用户，等待它的重新连接
                    //触发游戏中玩家退出事件
                    p.user.game.playerExit(p);
                }
            }
            //关闭该连接
            user.webSocket.close();
            System.out.println(user.name+"退出了系统,它当前进行的游戏类型为:"+user.gameType);
//            user=null;
            return true;
        }else{
            return false;
        }
    }

    public User getUserBySocket(WebSocket webSocket){
        for(User user: userCollection){
            if(user.webSocket == webSocket){
                return user;
            }
        }
        return null;
    }
}
